﻿using HalconDotNet;
using LeaderCCSLaserUI.Data;
using LeaderCCSLaserUI.Models;
using LeaderCCSLaserUI.Services;
using MotionRobot.Models;
using Newtonsoft.Json;
using NLog;
using Prism.Commands;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Text.Unicode;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Media;
using ViewROI;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar;
using MessageBox = System.Windows.Forms.MessageBox;

namespace LeaderCCSLaserUI.ViewModels.Dialogs
{
    public class BarcodeScanDialogViewModel : DialogViewModel
    {
        #region 变量
        private Param systemParam;
        private readonly IHIKCameraService leftCamera;
        private readonly IHIKCameraService rightCamera;
        private static Logger logger = LogManager.GetCurrentClassLogger();
        private CancellationTokenSource source1;
        private readonly IGTSCardService gTSCard;
        private readonly DrawROI drawROI;
        double mxYJogSpeed = 0, mzJogSpeed = 0, mz1SafePos, mz2SafePos;
        private bool isClosing = false;
        #endregion
        #region 属性
        private HImage cameraImage0;
        public HImage CameraImage0
        {
            get { return cameraImage0; }
            set { SetProperty(ref cameraImage0, value); }
        }
        private bool cameraRepaint0;
        public bool CameraRepaint0
        {
            get { return cameraRepaint0; }
            set { SetProperty(ref cameraRepaint0, value); }
        }
        private ObservableCollection<ROI> cameraROIList0 = new ObservableCollection<ROI>();
        public ObservableCollection<ROI> CameraROIList0
        {
            get { return cameraROIList0; }
            set { SetProperty(ref cameraROIList0, value); }
        }
        private HObject cameraAppendHObject0;
        public HObject CameraAppendHObject0
        {
            get { return cameraAppendHObject0; }
            set { SetProperty(ref cameraAppendHObject0, value); }
        }
        private HMsgEntry cameraAppendHMessage0;
        public HMsgEntry CameraAppendHMessage0
        {
            get { return cameraAppendHMessage0; }
            set { SetProperty(ref cameraAppendHMessage0, value); }
        }
        private Tuple<string, object> cameraGCStyle0;
        public Tuple<string, object> CameraGCStyle0
        {
            get { return cameraGCStyle0; }
            set { SetProperty(ref cameraGCStyle0, value); }
        }
        //PointList1
        private ObservableCollection<BarcodePointDisp> pointList1 = new ObservableCollection<BarcodePointDisp>();
        public ObservableCollection<BarcodePointDisp> PointList1
        {
            get { return pointList1; }
            set { SetProperty(ref pointList1, value); }
        }
        private BarcodePointDisp pointList1SelectedItem;
        public BarcodePointDisp PointList1SelectedItem
        {
            get { return pointList1SelectedItem; }
            set { SetProperty(ref pointList1SelectedItem, value); }
        }
        private bool isBusy;
        public bool IsBusy
        {
            get { return isBusy; }
            set { SetProperty(ref isBusy, value); }
        }
        private bool isDrawing;
        public bool IsDrawing
        {
            get { return isDrawing; }
            set { SetProperty(ref isDrawing, value); }
        }
        #endregion
        #region 方法
        private DelegateCommand openImageCommand;
        public DelegateCommand OpenImageCommand =>
            openImageCommand ?? (openImageCommand = new DelegateCommand(ExecuteOpenImageCommand));
        private DelegateCommand scanBarcodeCommand;
        public DelegateCommand ScanBarcodeCommand =>
            scanBarcodeCommand ?? (scanBarcodeCommand = new DelegateCommand(ExecuteScanBarcodeCommand));
        private DelegateCommand grabImageCommand;
        public DelegateCommand GrabImageCommand =>
            grabImageCommand ?? (grabImageCommand = new DelegateCommand(ExecuteGrabImageCommand));
        private DelegateCommand<object> liveGrabCommand;
        public DelegateCommand<object> LiveGrabCommand =>
            liveGrabCommand ?? (liveGrabCommand = new DelegateCommand<object>(ExecuteLiveGrabCommand));
        private DelegateCommand<object> pointList1RowEditEndingCommand;
        public DelegateCommand<object> PointList1RowEditEndingCommand =>
            pointList1RowEditEndingCommand ?? (pointList1RowEditEndingCommand = new DelegateCommand<object>(ExecutePointList1RowEditEndingCommand));
        private DelegateCommand<object> pointList1JumpPosCommand;
        public DelegateCommand<object> PointList1JumpPosCommand =>
            pointList1JumpPosCommand ?? (pointList1JumpPosCommand = new DelegateCommand<object>(ExecutePointList1JumpPosCommand));
        private DelegateCommand<object> pointList1GoPosCommand;
        public DelegateCommand<object> PointList1GoPosCommand =>
            pointList1GoPosCommand ?? (pointList1GoPosCommand = new DelegateCommand<object>(ExecutePointList1GoPosCommand));
        private DelegateCommand<object> pointList1DeleteCommand;
        public DelegateCommand<object> PointList1DeleteCommand =>
            pointList1DeleteCommand ?? (pointList1DeleteCommand = new DelegateCommand<object>(ExecutePointList1DeleteCommand));
        private DelegateCommand pointList1AddCommand;
        public DelegateCommand PointList1AddCommand =>
            pointList1AddCommand ?? (pointList1AddCommand = new DelegateCommand(ExecutePointList1AddCommand));
        private DelegateCommand<object> pointList1TeachPosCommand;
        public DelegateCommand<object> PointList1TeachPosCommand =>
            pointList1TeachPosCommand ?? (pointList1TeachPosCommand = new DelegateCommand<object>(ExecutePointList1TeachPosCommand));
        private DelegateCommand createRec1RegionComman;
        public DelegateCommand CreateRec1RegionCommand =>
            createRec1RegionComman ?? (createRec1RegionComman = new DelegateCommand(ExecuteCreateRec1RegionCommand));

        void ExecuteCreateRec1RegionCommand()
        {
            if (CameraImage0 != null)
            {
                if (PointList1SelectedItem != null)
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.BarcodePoints.FirstOrDefault(p => p.Id == PointList1SelectedItem.Id);
                    if (point != null)
                    {
                        if (MessageBox.Show($"确认要画识别区域吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                        {
                            try
                            {
                                IsDrawing = true;
                                var roi = drawROI.imageViewer.DrawROI(ROI.ROI_TYPE_RECTANGLE1);
                                IsDrawing = false;
                                if (!isClosing)
                                {
                                    var region = roi.getRegion();

                                    CameraAppendHObject0 = null;
                                    CameraGCStyle0 = new Tuple<string, object>("Color", "yellow");
                                    CameraGCStyle0 = new Tuple<string, object>("DrawMode", "margin");
                                    CameraAppendHObject0 = region;

                                    HOperatorSet.RegionFeatures(region, "row1", out var row1);
                                    HOperatorSet.RegionFeatures(region, "column1", out var column1);
                                    HOperatorSet.RegionFeatures(region, "row2", out var row2);
                                    HOperatorSet.RegionFeatures(region, "column2", out var column2);

                                    point.Rec1Row1 = Math.Round(row1.D, 0);
                                    point.Rec1Column1 = Math.Round(column1.D, 0);
                                    point.Rec1Row2 = Math.Round(row2.D, 0);
                                    point.Rec1Column2 = Math.Round(column2.D, 0);

                                    mdb.SaveChanges();
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }

                }
                else
                {
                    MessageBox.Show("请先选择点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("图像为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecutePointList1TeachPosCommand(object obj)
        {
            if (obj is BarcodePointDisp barcodepoint)
            {
                if (MessageBox.Show($"确认示教吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    switch ((int)barcodepoint.Hand)
                    {
                        case 0:
                            barcodepoint.X = Math.Round(GTSCard.GetEnc(gTSCard.A1), 3);
                            barcodepoint.Y = Math.Round(GTSCard.GetEnc(gTSCard.A2), 3);
                            barcodepoint.Z = Math.Round(GTSCard.GetEnc(gTSCard.A3), 3);
                            break;
                        case 1:
                        default:
                            barcodepoint.X = Math.Round(GTSCard.GetEnc(gTSCard.A5), 3);
                            barcodepoint.Y = Math.Round(GTSCard.GetEnc(gTSCard.A6), 3);
                            barcodepoint.Z = Math.Round(GTSCard.GetEnc(gTSCard.A7), 3);
                            break;
                    }
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.BarcodePoints.FirstOrDefault(p => p.Id == barcodepoint.Id);
                    if (point != null)
                    {
                        point.X = barcodepoint.X;
                        point.Y = barcodepoint.Y;
                        point.Z = barcodepoint.Z;
                        mdb.SaveChanges();
                    }
                }
            }
        }
        void ExecutePointList1AddCommand()
        {
            DialogParameters param = new DialogParameters();
            dialogService.ShowDialog("AddBarcodePointDialog", param, arg => {
                if (arg.Result == ButtonResult.Yes)
                {
                    try
                    {
                        HandEnum Hand = arg.Parameters.GetValue<HandEnum>("Hand");
                        BarcodeEnum Kind = arg.Parameters.GetValue<BarcodeEnum>("Kind");
                        double X = arg.Parameters.GetValue<double>("X");
                        double Y = arg.Parameters.GetValue<double>("Y");
                        double Z = arg.Parameters.GetValue<double>("Z");
                        ProductEnum ProductIndex = arg.Parameters.GetValue<ProductEnum>("ProductIndex");
                        double ExposureTime = arg.Parameters.GetValue<double>("ExposureTime");
                        bool UseLight1 = arg.Parameters.GetValue<bool>("UseLight1");
                        bool UseLight2 = arg.Parameters.GetValue<bool>("UseLight2");
                        using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                        BarcodePoint barcodePoint = new BarcodePoint
                        {
                            Hand = Hand == HandEnum.左 ? 0 : 1,
                            ProductIndex = (int)ProductIndex,
                            X = X,
                            Y = Y,
                            Z = Z,
                            ExposureTime = ExposureTime,
                            Kind = Kind == BarcodeEnum.产品码 ? 0 : 1,
                            UseLight1 = UseLight1,
                            UseLight2 = UseLight2,
                            Rec1Row1 = 2048 / 2 - 100,
                            Rec1Column1 = 2448 / 2 - 100,
                            Rec1Row2 = 2048 / 2 + 100,
                            Rec1Column2 = 2448 / 2 + 100
                        };
                        mdb.BarcodePoints.Add(barcodePoint);
                        mdb.SaveChanges();
                        LoadPoint();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }
        void ExecutePointList1DeleteCommand(object obj)
        {
            if (obj is BarcodePointDisp barcodepoint)
            {
                if (MessageBox.Show("确认删除点位吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    try
                    {
                        using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                        var point = mdb.BarcodePoints.FirstOrDefault(p => p.Id == barcodepoint.Id);
                        if (point != null)
                        {
                            mdb.BarcodePoints.Remove(point);
                            mdb.SaveChanges();
                        }
                        var pointdisp = PointList1.FirstOrDefault(p => p.Id == barcodepoint.Id);
                        if (pointdisp != null)
                        {
                            PointList1.Remove(pointdisp);
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    
                }
            }
        }
        async void ExecutePointList1GoPosCommand(object obj)
        {
            if (obj is BarcodePointDisp barcodepoint)
            {
                if (MessageBox.Show("确认Go运动吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    AxisParm axisX, axisY, axisZ;
                    switch ((int)barcodepoint.Hand)
                    {
                        case 0:
                            axisX = gTSCard.A1;
                            axisY = gTSCard.A2;
                            axisZ = gTSCard.A3;
                            break;
                        case 1:
                        default:
                            axisX = gTSCard.A5;
                            axisY = gTSCard.A6;
                            axisZ = gTSCard.A7;
                            break;
                    }
                    GTSCard.ServoOn(axisX);//X
                    GTSCard.ServoOn(axisY);//Y
                    GTSCard.ServoOn(axisZ);//Z
                    GTSCard.AxisPosSet(axisX, GTSCard.GetEnc(axisX));
                    GTSCard.AxisPosSet(axisY, GTSCard.GetEnc(axisY));
                    GTSCard.AxisPosSet(axisZ, GTSCard.GetEnc(axisZ));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => GoAction(token, barcodepoint.X, barcodepoint.Y, barcodepoint.Z, axisX, axisY, axisZ), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        async void ExecutePointList1JumpPosCommand(object obj)
        {
            if (obj is BarcodePointDisp barcodepoint)
            {
                if (MessageBox.Show("确认Jump运动吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == System.Windows.Forms.DialogResult.Yes)
                {
                    IsBusy = true;
                    AxisParm axisX, axisY, axisZ;
                    double zSafePos;
                    switch ((int)barcodepoint.Hand)
                    {
                        case 0:
                            axisX = gTSCard.A1;
                            axisY = gTSCard.A2;
                            axisZ = gTSCard.A3;
                            zSafePos = mz1SafePos;
                            break;
                        case 1:
                        default:
                            axisX = gTSCard.A5;
                            axisY = gTSCard.A6;
                            axisZ = gTSCard.A7;
                            zSafePos = mz2SafePos;
                            break;
                    }
                    GTSCard.ServoOn(axisX);//X
                    GTSCard.ServoOn(axisY);//Y
                    GTSCard.ServoOn(axisZ);//Z
                    GTSCard.AxisPosSet(axisX, GTSCard.GetEnc(axisX));
                    GTSCard.AxisPosSet(axisY, GTSCard.GetEnc(axisY));
                    GTSCard.AxisPosSet(axisZ, GTSCard.GetEnc(axisZ));
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    await Task.Run(() => JumpAction(token, barcodepoint.X, barcodepoint.Y, barcodepoint.Z, axisX, axisY, axisZ, zSafePos), token).ContinueWith(t => { IsBusy = false; });
                }
            }
        }
        void ExecutePointList1RowEditEndingCommand(object obj)
        {
            if (obj is BarcodePointDisp barcodepoint)
            {
                try
                {
                    using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                    var point = mdb.BarcodePoints.FirstOrDefault(p => p.Id == barcodepoint.Id);
                    if (point != null)
                    {
                        point.X = barcodepoint.X;
                        point.Y = barcodepoint.Y;
                        point.Z = barcodepoint.Z;
                        point.UseLight1 = barcodepoint.UseLight1;
                        point.UseLight2 = barcodepoint.UseLight2;
                        point.ProductIndex = (int)barcodepoint.ProductIndex;
                        point.Kind = (int)barcodepoint.Kind;
                        point.ExposureTime = barcodepoint.ExposureTime;
                        point.Hand = (int)barcodepoint.Hand;
                        mdb.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("请先选择点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        void ExecuteLiveGrabCommand(object obj)
        {
            if (PointList1SelectedItem != null)
            {
                if ((bool)obj)
                {
                    source1 = new CancellationTokenSource();
                    CancellationToken token = source1.Token;
                    Task.Run(() => ContinueGrab(token, (int)PointList1SelectedItem.Hand, PointList1SelectedItem.ExposureTime), token);
                    IsBusy = true;
                }
                else
                {
                    if (source1 != null)
                    {
                        source1.Cancel();
                    }
                    IsBusy = false;
                }
            }
            else
            {
                MessageBox.Show("请先选择点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        async void ExecuteGrabImageCommand()
        {
            if (PointList1SelectedItem != null)
            {
                IHIKCameraService cameraService = PointList1SelectedItem.Hand == 0 ? leftCamera : rightCamera;
                IsBusy = true;
                cameraService.ImageQueue.Clear();
                cameraService.SetTriggerMode(0);
                cameraService.SetExposureTime((float)PointList1SelectedItem.ExposureTime);
                cameraService.StartGrabe();
                await Task.Run(() => {
                    int mIndex = 0;
                    while (mIndex < 1)
                    {
                        HObject? hObj;
                        if (cameraService.ImageQueue.TryPeek(out hObj))
                        {
                            cameraService.ImageQueue.TryDequeue(out hObj);
                            CameraImage0 = new HImage(hObj);
                            mIndex++;
                        }
                    }
                }).ContinueWith(t => { cameraService.StopGrabe(); IsBusy = false; });
            }
            else 
            {
                MessageBox.Show("请先选择点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteScanBarcodeCommand()
        {
            if (CameraImage0 != null)
            {
                if (PointList1SelectedItem != null)
                {
                    try
                    {
                        using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
                        var point = mdb.BarcodePoints.FirstOrDefault(p => p.Id == PointList1SelectedItem.Id);
                        if (point != null)
                        {
                            CameraAppendHObject0 = null;
                            CameraAppendHMessage0 = null;
                            HOperatorSet.CreateDataCode2dModel("QR Code", new HTuple(), new HTuple(), out var DataCodeHandle);
                            HOperatorSet.SetDataCode2dParam(DataCodeHandle, "polarity", "any");
                            HOperatorSet.SetDataCode2dParam(DataCodeHandle, "timeout", 200);
                            HOperatorSet.SetDataCode2dParam(DataCodeHandle, "string_encoding", "locale");
                            CameraGCStyle0 = new Tuple<string, object>("Color", "cornflower blue");
                            HOperatorSet.GenRectangle1(out var rec1, point.Rec1Row1, point.Rec1Column1, point.Rec1Row2, point.Rec1Column2);
                            CameraAppendHObject0 = rec1;
                            HOperatorSet.ReduceDomain(CameraImage0, rec1, out var imageReduced);
                            HOperatorSet.FindDataCode2d(imageReduced, out var symbolXLD1, DataCodeHandle, new HTuple(), new HTuple(), out var ResultHandles, out var DecodedDataStrings);
                            HOperatorSet.ClearDataCode2dModel(DataCodeHandle);
                            if (DecodedDataStrings.TupleLength() > 0)
                            {
                                CameraGCStyle0 = new Tuple<string, object>("Color", "green");
                                CameraAppendHObject0 = symbolXLD1;
                                string bar = DecodedDataStrings.TupleSelect(0).S.Replace(" ", string.Empty);
                                
                                CameraAppendHMessage0 = new HMsgEntry(bar, 10, 10, "magenta", "window", "box", "false", 24, "mono", "true", "false");
                            }
                            else
                            {
                                CameraAppendHMessage0 = new HMsgEntry($"NG", 40, 40, "orange red", "window", "box", "false", 24, "mono", "true", "false");
                            }
                        }

                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                else
                {
                    MessageBox.Show("请先选择点位", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
               
                
            }
            else
            {
                MessageBox.Show("图像为空", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        void ExecuteOpenImageCommand()
        {
            //int index = int.Parse(obj.ToString());
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Image Files|*.png;*.bmp;*.jpg;*.tif";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                HOperatorSet.ReadImage(out var mimage1, openFileDialog.FileName);
                CameraImage0 = new HImage(mimage1);
            }
        }
        #endregion
        #region 导航
        public override void OnDialogClosed()
        {
            if (source1 != null)
            {
                source1.Cancel();
            }
            leftCamera.StopGrabe();
            rightCamera.StopGrabe();

            isClosing = true;
            if (IsDrawing)
            {
                MFunc.HIOCancelDraw();
            }
        }

        public override void OnDialogOpened(IDialogParameters parameters)
        {
            LoadParam();
            LoadFromDb();
            LoadPoint();
        }
        #endregion
        #region 构造函数
        public BarcodeScanDialogViewModel(IContainerProvider containerProvider) : base(containerProvider)
        {
            Title = "扫码设置";
            IsBusy = false;
            IsDrawing = false;
            leftCamera = containerProvider.Resolve<IHIKCameraService>("LeftCamera");
            rightCamera = containerProvider.Resolve<IHIKCameraService>("RightCamera");
            gTSCard = containerProvider.Resolve<IGTSCardService>("GTSCard");
            drawROI = containerProvider.Resolve<DrawROI>();
        }
        #endregion
        #region 功能函数
        void LoadParam()
        {
            try
            {
                //Json序列化，从文件读取
                string jsonString = File.ReadAllText(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "Param.json"));
                systemParam = JsonConvert.DeserializeObject<Param>(jsonString);
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }
        }
        void LoadPoint()
        {
            PointList1.Clear();
            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
            var barcodePoints = mdb.BarcodePoints.Where(p => p.Id > 0);
            if (barcodePoints.Any())
            {
                barcodePoints.ToList().ForEach(p => {
                    PointList1.Add(new BarcodePointDisp
                    {
                        Id = p.Id,
                        Hand = (HandEnum)p.Hand,
                        Kind = (BarcodeEnum)p.Kind,
                        ProductIndex = (ProductEnum)p.ProductIndex,
                        ExposureTime = p.ExposureTime,
                        UseLight1 = p.UseLight1,
                        UseLight2 = p.UseLight2,
                        X = p.X,
                        Y = p.Y,
                        Z = p.Z
                    });
                });
            }
        }
        void LoadFromDb()
        {
            using var mdb = new MDbContext(systemParam.PartList[systemParam.PartIndex]);
            var _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "XYJogSpeed");
            if (_mParam != null)
            {
                mxYJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZJogSpeed");
            if (_mParam != null)
            {
                mzJogSpeed = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 0);
            if (_mParam != null)
            {
                mz1SafePos = double.Parse(_mParam.Value);
            }
            _mParam = mdb.MParams.FirstOrDefault(m => m.Name == "ZSafePos" && m.Hand == 1);
            if (_mParam != null)
            {
                mz2SafePos = double.Parse(_mParam.Value);
            }
        }
        private void ContinueGrab(CancellationToken token,int handIndex,double exposureTime)
        {
            IHIKCameraService cameraService = handIndex == 0 ? leftCamera : rightCamera;
            cameraService.ImageQueue.Clear();
            cameraService.SetTriggerMode(0);
            cameraService.SetExposureTime((float)exposureTime);
            cameraService.StartGrabe();
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    cameraService.StopGrabe();
                    return;
                }
                HObject? hObj;
                if (cameraService.ImageQueue.TryPeek(out hObj))
                {
                    cameraService.ImageQueue.TryDequeue(out hObj);
                    CameraImage0 = new HImage(hObj);
                }
                System.Threading.Thread.Sleep(1);
            }
        }
        private void JumpAction(CancellationToken token, double tartgetX, double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ, double ZSafe)
        {
            try
            {
                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0://Z运动到安全位
                            {
                                GTSCard.AxisPosMove(ref axisZ, ZSafe, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                stepnum = 2;
                            }
                            break;
                        case 2:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                stepnum = 3;
                            }
                            break;
                        case 3:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY))
                            {
                                stepnum = 4;
                            }
                            break;
                        case 4:
                            {
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 5;
                            }
                            break;
                        case 5:
                            if (GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }
        }
        private void GoAction(CancellationToken token, double tartgetX, double tartgetY, double tartgetZ, AxisParm axisX, AxisParm axisY, AxisParm axisZ)
        {
            try
            {
                int stepnum = 0;
                while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    switch (stepnum)
                    {
                        case 0:
                            {
                                GTSCard.AxisPosMove(ref axisX, tartgetX, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisY, tartgetY, mxYJogSpeed);
                                GTSCard.AxisPosMove(ref axisZ, tartgetZ, mzJogSpeed);
                                stepnum = 1;
                            }
                            break;
                        case 1:
                            if (GTSCard.AxisPosMoveCheckDone(axisX) && GTSCard.AxisPosMoveCheckDone(axisY) &&
                                GTSCard.AxisPosMoveCheckDone(axisZ))
                            {
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                    System.Threading.Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
                Debug.WriteLine(ex.Message);
            }

        }
        #endregion
    }
}
